import { Button, Carousel, Empty, Steps, Tabs, TabsProps, Tag, Tooltip } from 'antd'
import './style.css'
import demendtitel from '../../assets/demendtitle.png'
import { HsAdminInput, HsAdminSpin } from '@hs-admin/base-components'
import { getDataBaseHistoryList } from '../../../../dataService/src/api/overview'
import { useEffect, useRef, useState } from 'react'
import CompanyModel from './components/CompanyList'
import { MonitorsList } from '@hs-server/components'
import { Mytable } from '@hs-server/components'
import warning from '/src/assets/warning.png'
import addmonitor from '/src/assets/addmonitor.png'
import Monitoring_successful from '/src/assets/Monitoring_successful.png'
import primary from '/src/assets/primary.png'
import banner1 from '/src/assets/banner.png'
import banner2 from '/src/assets/bannertow.png'
import { getLatest_monitoringdata, alarm_recommend, monitorList, addmonitorsitems, has_datas, hot_monitor_track, deletemonitors } from '@/api/home'
import InfiniteScroll from 'react-infinite-scroll-component'
import { openCompanyDetail } from 'hs-react-company'
import { Typography } from 'antd'
import { useNavigate } from 'react-router-dom'
import { DetailModal, useAddDemandOrder } from '@hs-server/components'
import { message } from '@hs-admin/utils'

const { Text } = Typography

const HomePage = () => {
  //获取最新监测
  const [latest_monitoring, setlatest_monitoring]: any = useState([])

  const [TableData, setTableData]: any = useState([])

  //获取预警企业
  const [getWarningEnterprise, setgetWarningEnterprise]: any = useState([])

  //获取推荐企业
  const [getEnterpriselist, setgetEnterpriselist]: any = useState([])

  const [keywordsHistory, setkeywordsHistory] = useState<any[]>([])

  const [keywords, setkeywords] = useState('')

  const [source_id, setsource_id] = useState('')

  const [source_name, setsource_name] = useState('')

  const [ismonitor, setismonitor] = useState(false)

  const companyRef: any = useRef({})

  const conitorsListRef: any = useRef({})

  const [active, setactive]: any = useState([])

  const [tabsKey, settabsKey]: any = useState('全部')

  const [termsactive, settermsactive]: any = useState(30)

  const [gettermsactive, setgettermsactive]: any = useState(30)

  const [hasMore, setHasMore] = useState(false)

  const [EnterpriseLishasMore, setEnterpriseLishasMore] = useState(false)

  const [getishasMore, setgetishasMore] = useState(false)

  const [loading, setloading] = useState(false)

  const [loading1, setloading1] = useState(false)

  const DetailModalRef = useRef<any>(null)

  const [pagination, setpagination] = useState({
    current: 1,
    pageSize: 20
  })

  const [pagination2, setpagination2] = useState({
    current: 1,
    pageSize: 20
  })

  const [pagination3, setpagination3] = useState({
    current: 1,
    pageSize: 20
  })

  const contentStyle: React.CSSProperties = {
    height: '320px',
    width: '100%',
    color: '#fff',
    lineHeight: '320px',
    textAlign: 'center',
    background: '#364d79',
    borderRadius: '6px'
  }

  const items: any = [
    {
      key: '全部',
      label: '全部'
    },
    {
      key: '预警',
      label: '预警'
    },
    {
      key: '利好',
      label: '利好'
    }
  ]

  const items2: TabsProps['items'] = [
    {
      key: '30天内',
      label: '30天内',
      children: <EnterpriseList list={getWarningEnterprise} type="预警" />
    },
    {
      key: '7天内',
      label: '7天内',
      children: <EnterpriseList list={getWarningEnterprise} type="预警" />
    }
  ]

  const items3: TabsProps['items'] = [
    {
      key: '30天内',
      label: '30天内',
      children: <EnterpriseList list={getEnterpriselist} type="利好" />
    },
    {
      key: '7天内',
      label: '7天内',
      children: <EnterpriseList list={getEnterpriselist} type="利好" />
    }
  ]

  //热门赛道
  const DataTablecolumns = [
    {
      title: '赛道名称',
      dataIndex: 'map_name',
      ellipsis: true,
      render: (text: string, record: any) => {
        return (
          <Text
            ellipsis={{ tooltip: true }}
            className="cursor-pointer text-#0779ff"
            onClick={() => {
              const { released_map = {} } = record
              let platforms = released_map?.platforms || []
              platforms = platforms.filter((item: { name: string | string[] }) => item.name.includes('产业预警通'))
              if (!platforms.length) {
                message.warning('缺少数据暂无法跳转')
                return
              }
              const routeInfor: any = {
                '产业预警通-生物医药专区': '/biomedicalArea',
                '产业预警通-新能源专区': '/newEnergy',
                '产业预警通-汽车专区': '/carArea',
                '产业预警通-新材料专区': '/advancedMaterialArea',
                '产业预警通-未来产业专区': '/futureArea',
                '产业预警通-数字经济专区': '/digitalEconomy',
                '产业预警通-高端装备专区': '/highEquipment',
                '产业预警通-农业专区': '/agriculture',
                '产业预警通-食品专区': '/food',
                '产业预警通-传统制造业专区': '/traditionaLindustry',
                '产业预警通-数字创意专区': '/digitalCreativity'
              }
              const page = routeInfor[platforms[0].name]
              navigate(`${page}?activeId=${record.released_map_id}&from=${record.map_name}&map_id=${record.map_id}`)
            }}>
            {text}
          </Text>
        )
      }
    },
    {
      title: '企业数量/家',
      dataIndex: 'count_tracks'
    }
  ]

  const { AddDemandOrder, showModal: showAddDemandOrderModal } = useAddDemandOrder()

  const onChange = (key: string) => {
    setpagination({
      current: 1,
      pageSize: 20
    })
    if (key === '预警') {
      setactive(['高风险', '警示'])
    } else if (key === '利好') {
      setactive(['利好'])
    } else {
      setactive([])
    }
  }

  function items2onChange(key: string) {
    if (key === '30天内') {
      settermsactive(30)
    } else if (key === '7天内') {
      settermsactive(7)
    } else {
      settermsactive('')
    }
  }

  function items3onChange(key: string) {
    if (key === '30天内') {
      setgettermsactive(30)
    } else if (key === '7天内') {
      setgettermsactive(7)
    } else {
      setgettermsactive('')
    }
  }

  const EnterpriseListData = () => {
    setpagination2({
      current: pagination2.current + 1,
      pageSize: 20
    })
  }

  const getEnterprisedata = () => {
    setpagination3({
      current: pagination3.current + 1,
      pageSize: 20
    })
  }

  const fetchData = () => {
    setpagination({
      current: pagination.current + 1,
      pageSize: 20
    })
  }

  const onSearch = (_value: string) => {
    goto(_value)
  }
  const navigate = useNavigate()
  const goto = (keywords: any) => {
    navigate(`/exploreCompany?keywords=${keywords}`)
  }
  const callDataService = () => {
    showAddDemandOrderModal()
  }

  //最新监测
  const getlatest_monitoring = () => {
    setloading(true)
    const data: any = {
      page: pagination.current,
      page_size: pagination.pageSize,
      cate: active
    }
    getLatest_monitoringdata(data)
      .then((res: any) => {
        setlatest_monitoring((prev: any) => {
          if (pagination.current === 1) {
            prev = res.items
          } else {
            prev = [...prev, ...res.items]
          }
          const arr: any = []
          res.items.forEach((_item: any, index: any) => {
            arr.push(getmonitorList(_item.source_id, index))
          })
          Promise.all(arr).then((res: any) => {
            gethas_datas(res, 'monitor')
          })
          return [...prev]
        })
        setloading(false)
        if (res.total > pagination.current * pagination.pageSize) {
          setHasMore(true)
        } else {
          setHasMore(false)
        }
      })
      .finally(() => {
        setloading(false)
      })
  }

  //获取是否监测 type:monitor 最新监测, Enterprise:企业列表 isEnterprise:警示/利好
  const gethas_datas = async (item: any, type: any, _isEnterprise?: any) => {
    let arr: any = []
    if (type === 'monitor') {
      item.map((_item: any, _index: any) => {
        _item.items.map((item: any) => {
          if (item.company_code) arr.push(item.company_code)
        })
      })
      const res = await has_datas({ data_ids: arr })
      setlatest_monitoring((prev: any) => {
        prev.map((_item: any) => {
          _item.company_list?.items.map((its: any) => {
            Object.keys(res).map((key: any) => {
              if (key === its.company_code) its.has_monitored = res[its.company_code]
            })
          })
        })
        return [...prev]
      })
    } else {
      arr = item.map((item: any, _index: any) => item.company_code && item.company_code)
      const res = await has_datas({ data_ids: arr })
      if (_isEnterprise === '利好') {
        setgetEnterpriselist((prev: any) => {
          prev.map((item: any) => {
            item.has_monitored = res[item.company_code]
          })
          return [...prev]
        })
      } else {
        setgetWarningEnterprise((prev: any) => {
          prev.map((item: any) => {
            item.has_monitored = res[item.company_code]
          })
          return [...prev]
        })
      }
    }
  }

  //推荐企业
  const getalarm_recommend = () => {
    setloading1(true)
    const data: any = {
      page: pagination2.current,
      page_size: pagination2.pageSize,
      want_days: gettermsactive,
      terms: ['利好']
    }
    alarm_recommend(data)
      .then((res: any) => {
        setgetEnterpriselist((prev: any) => {
          if (pagination2.current === 1) {
            prev = res.items
          } else {
            prev = [...prev, ...res.items]
          }
          gethas_datas(prev, 'Enterprise', '利好')
          return [...prev]
        })
        if (res.total > pagination2.current * pagination2.pageSize) {
          setEnterpriseLishasMore(true)
        } else {
          setEnterpriseLishasMore(false)
        }
        setloading1(false)
      })
      .finally(() => {
        setloading1(false)
      })
  }

  //预警推荐企业
  const getEnterprise = () => {
    setloading1(true)
    const data: any = {
      page: pagination3.current,
      page_size: pagination3.pageSize,
      want_days: termsactive,
      terms: ['高风险', '警示']
    }
    alarm_recommend(data)
      .then((res: any) => {
        setgetWarningEnterprise((prev: any) => {
          if (pagination3.current === 1) {
            prev = res.items
          } else {
            prev = [...prev, ...res.items]
          }
          gethas_datas(prev, 'Enterprise', '警示')
          return [...prev]
        })
        if (res.total > pagination3.current * pagination3.pageSize) {
          setgetishasMore(true)
        } else {
          setgetishasMore(false)
        }
      })
      .finally(() => {
        setloading1(false)
      })
  }

  //打开最新监测详情弹框
  function handleDetail(_item: any) {
    const obj = {
      ..._item,
      eventSubType: _item.event_sub_type,
      id: _item.source_id,
      sourceTable: _item.source_table,
      eventSegment: _item.event_segment === '药品申请上市' ? '新药管线' : _item.event_segment,
      companyName: _item.company_name,
      company_name: _item.company_name,
      company_code: _item.company_code
    }
    DetailModalRef.current?.showModal(obj)
  }

  //获取热门赛道

  const gethot_monitor_track = () => {
    hot_monitor_track().then((res: any) => {
      setTableData(res)
    })
  }

  const getmonitorList = (id: any, _index?: any) => {
    return new Promise((resolve) => {
      const data: any = {
        page: 1,
        page_size: 2,
        id: id
      }
      monitorList(data).then((res: any) => {
        setlatest_monitoring((prev: any) => {
          prev.forEach((element: any) => element.source_id == id && (element.company_list = res.items.length ? res : []))
          return [...prev]
        })
        resolve(res)
      })
    })
  }

  const getStatusList = async () => {
    const res = await has_datas({ data_ids: [source_id] })
    setlatest_monitoring((prev: any) => {
      prev.map((item: any) => {
        item?.company_list?.items.map((item3: any) => {
          Object.keys(res).map((key: any) => {
            if (item3.company_code === key) {
              item3.has_monitored = res[key]
            }
          })
        })
      })
      return [...prev]
    })
  }

  const addmonitorsitem = (id: any) => {
    if (!ismonitor) {
      addmonitors_items(id)
    } else delemonitors(id)
  }

  const addmonitors_items = (id: any) => {
    addmonitorsitems({ data_id: source_id, list_id: id, data_name: source_name }).then((_res: any) => {
      message.success('监测成功')
      // 获取当前列表的标签列表 ，用于修改状态
      getStatusList()
      getalarm_recommend() //推荐企业
      getEnterprise() //预警企业
    })
  }

  const showModel = (id: any) => {
    companyRef.current.showModal(id)
  }

  const getsource = (source: any, ismonitor: boolean) => {
    setsource_id(source.id)
    setsource_name(source.name)
    setismonitor(ismonitor)
    conitorsListRef.current.showModal(!ismonitor ? null : source.id)
  }

  const delemonitors = (id: any) => {
    deletemonitors({ list_id: id, data_id: source_id }).then(() => {
      message.success('已取消监测')
      // 获取当前列表的标签列表 ，用于修改状态
      getStatusList()
      getalarm_recommend() //推荐企业
      getEnterprise() //预警企业
    })
  }

  useEffect(() => {
    getDataBaseHistoryList({}).then((res) => {
      // 历史搜索
      setkeywordsHistory([...res.latest_searched_history])
    })
  }, [])

  useEffect(() => {
    getalarm_recommend()
  }, [gettermsactive, pagination2])

  useEffect(() => {
    getEnterprise()
  }, [termsactive, pagination3])

  useEffect(() => {
    getlatest_monitoring()
  }, [active, pagination])

  useEffect(() => {
    gethot_monitor_track()
  }, [])

  //处理月日的方法
  const formatDate = (date: string) => {
    const month = date.slice(5, 7)
    const day = date.slice(8, 10)
    return `${month.replace('0', '')}月${day}日`
  }

  function EnterpriseList(props: any) {
    //type:预警 利好
    const { list, type } = props

    return (
      <div className="max-h-280px overflow-auto" id={type === '预警' ? 'scrollableDiv2' : 'scrollableDiv3'}>
        <InfiniteScroll
          dataLength={list.length}
          next={type === '预警' ? getEnterprisedata : EnterpriseListData}
          hasMore={type === '预警' ? getishasMore : EnterpriseLishasMore}
          loader={<h4>Loading...</h4>}
          scrollableTarget={type === '预警' ? 'scrollableDiv2' : 'scrollableDiv3'}>
          <div className="flex flex-wrap cursor-pointer">
            {list.length ? (
              list.map((_item: any, _index: number) => (
                <div key={_index} className="flex items-center mr-6% mb-15px w-44%" style={{ justifyContent: 'center' }}>
                  <div className="flex items-center">
                    <img className="w-14px h-18px" src={type === '预警' ? warning : primary} alt="" />
                    <div className="warning-title mx-7px" style={type !== '预警' ? { color: '#06DD71' } : { color: '#FF6666' }}>
                      {_item.total}
                    </div>
                  </div>
                  <Text className="warning-name w-60% mr-10px" ellipsis={{ tooltip: true }}>
                    <span onClick={() => openCompanyDetail(_item.company_code, 'industryWarning', '企业动态')}>
                      {_item.top_document?.company_name}
                    </span>
                  </Text>
                  <Tooltip title={_item.has_monitored ? '取消监测' : '加监测'}>
                    <div
                      className="flex items-center justify-end cursor-pointer"
                      style={{ flexShrink: 0 }}
                      onClick={() => getsource({ id: _item.company_code, name: _item.top_document?.company_name }, _item.has_monitored)}>
                      <img className="w-14px h-14px ml-11px" src={_item.has_monitored ? Monitoring_successful : addmonitor} alt="" />
                    </div>
                  </Tooltip>
                </div>
              ))
            ) : (
              <Empty className="ml-50%" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>
        </InfiniteScroll>
      </div>
    )
  }

  return (
    <div className="">
      <div className="home-container py-24px px-32px max-w-1400px mx-auto">
        <div className="top h-320px w-100%">
          <Carousel autoplay>
            <div onClick={() => window.open('https://mp.weixin.qq.com/s/qin56Fi-XRd0Ri-t_ayR8w', '_blank')}>
              <img style={contentStyle} src={banner1} alt="" />
            </div>
            <div onClick={() => window.open('https://mp.weixin.qq.com/s/_tjjY-CgMZDxSZaiP9cknQ', '_blank')}>
              <img style={contentStyle} src={banner2} alt="" />
            </div>
          </Carousel>
        </div>
        <div className="center pt-24px">
          <div className="Search flex items-center">
            <div className="left mr-16px pt-16px">
              <div>
                <div className="flex h-24px items-center">
                  <div className="icon mr-24px"></div>
                  <div className="text-18px font-bold title">企业查询</div>
                </div>
              </div>
              <div className="pt-24px px-42px flex items-center">
                <HsAdminInput
                  allowClear
                  value={keywords}
                  placeholder="输入关键词查询企业"
                  onChange={(e: any) => setkeywords(e.target.value)}
                  onPressEnter={() => onSearch(keywords)}
                />
                <Button className="ml-5px" type="primary" onClick={() => onSearch(keywords)}>
                  搜索
                </Button>
              </div>
              <div className="mx-auto mt-24px pl-42px history flex h-20px overflow-hidden">
                <span className="flex-none">搜索历史：</span>
                <div>
                  {keywordsHistory.length
                    ? keywordsHistory.map((item, index) => (
                        <Button type="link" size="small" key={index} className="max-w-30 history-name" onClick={() => onSearch(item)}>
                          {item}
                        </Button>
                      ))
                    : '暂无历史记录'}
                </div>
              </div>
            </div>
            <div className="right flex direction-column items-center justify-between px-40px">
              <div className="">
                <img className="w-218px h-36px" src={demendtitel} alt="" />
                <div className="demendtitle2">专业运营人员帮你整理数据！</div>
              </div>
              <div className="btn" onClick={callDataService}>
                去提交
              </div>
            </div>
          </div>
          <div className="center-bottom mt-16px flex justify-between">
            <div className="Latest_monitoring mr-16px py-24px">
              <div>
                <div className="flex h-24px items-center">
                  <div className="icon mr-24px"></div>
                  <div className="text-18px font-bold title">最新监测</div>
                </div>
              </div>
              <div className="pl-24px">
                <div className="pr-24px">
                  <div className="flex items-center mt-24px h-46px tabs">
                    {items.map((item: any) => (
                      <div
                        className={`${tabsKey === item.key ? 'active' : ''} mr-24px tab-item`}
                        key={item.key}
                        onClick={() => {
                          onChange(item.key)
                          settabsKey(item.key)
                          setlatest_monitoring([])
                        }}>
                        {item.label}
                      </div>
                    ))}
                  </div>
                </div>
                <div id="dataAll" className="max-h-480px overflow-auto">
                  {loading && <HsAdminSpin />}
                  <InfiniteScroll
                    dataLength={latest_monitoring.length}
                    next={fetchData}
                    hasMore={hasMore}
                    loader={<h4>Loading...</h4>}
                    scrollableTarget="dataAll">
                    <Steps
                      progressDot
                      current={latest_monitoring.length - 1}
                      direction="vertical"
                      items={latest_monitoring.map((item: any) => ({
                        title: (
                          <div>
                            <div className="text-14px font">{formatDate(item.occur_date)}</div>
                            <div className="flex items-center">
                              <div className="title cursor-pointer" onClick={() => handleDetail(item)}>
                                {item.event_title}
                                <Tag className="ml-10px" color={item.event_quality === '利好' ? 'green' : 'red'}>
                                  {item.event_quality === '利好' ? '利好' : '预警'}
                                </Tag>
                              </div>
                            </div>
                            <div className="mt-6px flex" style={{ color: '#999999' }}>
                              {item?.company_list?.items?.length
                                ? item?.company_list?.items?.map(
                                    (its: any, index: any) =>
                                      its.company_name && (
                                        <Tag key={index} className="ml-10px flex items-center justify-between h-32px">
                                          <div
                                            className="font-bold text-blue cursor-pointer"
                                            style={{ color: '595959' }}
                                            onClick={() => openCompanyDetail(its.company_code, 'industryWarning', '企业动态')}>
                                            {its.company_name ?? '--'}
                                          </div>
                                          <div
                                            className="flex items-center cursor-pointer"
                                            onClick={() => getsource({ id: its.company_code, name: its.company_name }, its.has_monitored)}>
                                            <img
                                              className="w-14px h-14px ml-11px"
                                              src={its.has_monitored ? Monitoring_successful : addmonitor}
                                              alt=""
                                            />
                                            <div className={`ml-7px ${its.has_monitored ? 'text-blue' : ''}`}>
                                              {its.has_monitored ? '已监测' : '加监测'}
                                            </div>
                                          </div>
                                        </Tag>
                                      )
                                  )
                                : ''}
                              {item?.company_list?.items?.length > 2 && (
                                <span className="text-blue ml-10px cursor-pointer" onClick={() => showModel(item.source_id)}>
                                  查看全部
                                </span>
                              )}
                            </div>
                          </div>
                        ),
                        description: item.description,
                        status: item.status
                      }))}
                    />
                  </InfiniteScroll>
                </div>
              </div>
            </div>
            <div className="Popular_tracks py-24px">
              <div className="flex h-24px items-center">
                <div className="icon mr-24px"></div>
                <div className="text-18px font-bold title">热门赛道</div>
              </div>
              <Mytable columns={DataTablecolumns} rowKey="map_id" data={TableData} />
            </div>
          </div>
        </div>
        <div className="bottom flex items-center justify-between mt-16px">
          <div className="w-50% h-450px bg-white mr-16px py-24px">
            <div>
              <div className="flex h-24px items-center">
                <div className="icon mr-24px"></div>
                <div className="text-18px font-bold title">预警企业</div>
              </div>
              <div className="pl-24px">
                {loading1 && <HsAdminSpin />}
                <Tabs className="mt-16px" defaultActiveKey="1" items={items2} onChange={items2onChange} />
              </div>
            </div>
          </div>
          <div className="w-50% h-450px bg-white py-24px">
            <div>
              <div className="flex h-24px items-center">
                <div className="icon mr-24px"></div>
                <div className="text-18px font-bold title">推荐企业</div>
              </div>
              <div className="pl-24px">
                <Tabs className="mt-16px" defaultActiveKey="1" items={items3} onChange={items3onChange} />
              </div>
            </div>
          </div>
        </div>
        <CompanyModel ref={companyRef} isModal={getlatest_monitoring} />
        <MonitorsList ref={conitorsListRef} addmonitorsitem={addmonitorsitem} />
        <DetailModal ref={DetailModalRef} />
      </div>
      {AddDemandOrder}
    </div>
  )
}
export default HomePage
